package com.jty.module_login.viewmodel

import android.util.Log
import android.view.View
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.lib_base.config.AppConstants
import com.jty.lib_base.base.BaseBean
import com.jty.lib_base.base.BaseViewModel
import com.jty.lib_base.base.MyApplication
import com.jty.lib_base.binding.command.BindingAction
import com.jty.lib_base.binding.command.BindingCommand
import com.jty.lib_base.binding.command.BindingConsumer
import com.jty.lib_base.bus.event.SingleLiveEvent
import com.jty.lib_base.data.DataRepository
import com.jty.lib_base.data.bean.LoginBean
import com.jty.lib_base.data.bean.UserInfoBean
import com.jty.lib_base.event.LiveBusCenter
import com.jty.lib_base.extension.ApiSubscriptHelper
import com.jty.lib_base.room.AppDatabase
import com.jty.lib_base.route.RouteCenter
import com.jty.lib_base.utils.ComUtils
import com.jty.lib_base.utils.RxThreadHelper
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import okhttp3.RequestBody
import java.util.concurrent.TimeUnit


/**
 * author: zhouyh
 * created on: 2021/9/14 11:08 上午
 * description: 登录模块viewModel
 */
class LoginViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var account = ObservableField("")  //tch817378304 tch05659908
    var password = ObservableField("")

    val savePwdState: ObservableBoolean = ObservableBoolean(model.getPwdFlag())
    val eyeState: ObservableBoolean = ObservableBoolean(false)

    val uc = UIChangeEvent()

    /**
     * UI刷新事件 用于观察者
     */
    class UIChangeEvent {
        val passwordVisibleEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
        val keepAccountEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    }

    override fun onResume() {
        super.onResume()
        model.outLoginReset()

        Observable.timer(300, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : Observer<Long> {
                override fun onSubscribe(d: Disposable) {}
                override fun onNext(aLong: Long) {
                    //LiveBusCenter.postToPenNoSubmitEvent() //为了程序奔溃导致笔记没有提交到后台，笔记预览做了每1分钟保存到本地
                    LiveBusCenter.postToVersionUpdateEvent(false)
                }

                override fun onError(e: Throwable) {}
                override fun onComplete() {}
            })
    }

    val onAccountChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        account.set(it)
    })

    val onPasswordChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        password.set(it)
    })

    val onLoginClick: BindingCommand<Any> = BindingCommand(BindingAction {
        loginByPwd();
    })

    val onResetPwdClickCommand: BindingCommand<Any> = BindingCommand(BindingAction {
        startContainerActivity(AppConstants.Router.Login.F_RESET_PWD)
    })

    val onSavePwdClickCommand: View.OnClickListener = View.OnClickListener {
        if (savePwdState.get()) {
            savePwdState.set(false)
        } else {
            savePwdState.set(true)
        }
        uc.keepAccountEvent.postValue(savePwdState.get())
    }

    val onClearClickCommand: View.OnClickListener = View.OnClickListener {
        account.set("")
    }

    val onEyeClickCommand: BindingCommand<Void> = BindingCommand(BindingAction {
        if (eyeState.get()) {
            eyeState.set(false)
        } else {
            eyeState.set(true)
        }
        uc.passwordVisibleEvent.postValue(eyeState.get())
    })


    /**
     * 登录
     */
    private fun loginByPwd() {
        if (account.get().isNullOrBlank() || password.get().isNullOrBlank()) {
            showNormalToast("账号密码不能为空")
            return
        }
        val json = ComUtils.getHashmapByStr(
            arrayOf( "mobile","password"),
            arrayOf(account.get().toString(),password.get().toString())
        )
        val requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
            GsonUtils.toJson(json))
        model.login(requestBody)
            .doOnSubscribe { showLoading("登录中...") }
            .compose(RxThreadHelper.rxSchedulerHelper(this@LoginViewModel))
            .subscribe(object : ApiSubscriptHelper<BaseBean<LoginBean>>() {
                override fun onResult(t: BaseBean<LoginBean>) {
                    dismissLoading()
                    if (t.code == 0) {
                        AppDatabase.resetInstance()
                        t.data?.let {
                            model.saveLoginData(it)
                        }
                        if (savePwdState.get()){
                            model.saveAccountAndPwd(account.get()!!, password.get()!!)
                        }
                        LiveBusCenter.postLoginSuccessEvent()
                        RouteCenter.navigate(AppConstants.Router.Main.A_MAIN)
                        model.saveLoginState(true)
                        finish()

                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                }
            })
    }
}

